#include "checkerboardwidget.h"

#include <QPainter>

CheckerboardWidget::CheckerboardWidget(QWidget *parent) :
    QWidget(parent)
{
    m_WidthSize = 0;
    m_HeightSize = 0;

    m_ctrl = NULL;


    connect(&m_UpdateTimer, SIGNAL(timeout()), this, SLOT(update()));
    m_UpdateTimer.setInterval(100);
    m_UpdateTimer.start();


}

void CheckerboardWidget::setControl(CControl* ctrl)
{
    m_ctrl = ctrl;

    m_ctrl->GetSize(m_WidthSize, m_HeightSize);
}

///
/// \brief CheckerboardWidget::paintEvent
/// 重绘事件
///
void CheckerboardWidget::paintEvent(QPaintEvent *)
{
    if (m_WidthSize <= 0 || m_HeightSize <= 0 || m_ctrl == NULL)
    {
        return ;
    }

    QPainter painter(this);

    m_everyChecherWidth = 1.0f * (this->rect().width() - 1) / m_WidthSize;
    m_everyChecherHeight = 1.0f * (this->rect().height() - 1) / m_HeightSize;

    // 绘制矩阵的格子
    for (int i = 0; i <= m_WidthSize; i++)
    {
        QPoint startPoint(i * m_everyChecherWidth, this->rect().top());
        QPoint endPoint(i * m_everyChecherWidth, this->rect().bottom());
        painter.drawLine(startPoint, endPoint);
    }

    for (int i = 0; i <= m_HeightSize; i++)
    {
        QPoint startPoint(this->rect().left(), i * m_everyChecherHeight);
        QPoint endPoint(this->rect().right(), i * m_everyChecherHeight);
        painter.drawLine(startPoint, endPoint);
    }

    for (int i = 0; i < m_WidthSize; i++)
    {
        for (int j = 0; j < m_HeightSize; j++)
        {
            float x, y;
            x = i *  m_everyChecherWidth;
            y = j * m_everyChecherHeight;
            CBall *pBall = NULL;
            if (m_ctrl->GetBall(pBall, i , j) == true)
            {
                pBall->drawBall(painter, QRectF(x, y, m_everyChecherWidth, m_everyChecherHeight));
            }
        }
    }

}



///
/// \brief CheckerboardWidget::mousePressEvent
/// 鼠标的点击事件
/// 选中 移动 小球
///
/// \param e
///
void CheckerboardWidget::mousePressEvent(QMouseEvent *e)
{
    QPoint pos = e->pos();

    int xIdx = pos.x() / m_everyChecherWidth;
    int yIdx = pos.y() / m_everyChecherHeight;

    xIdx = qMax(0, xIdx);
    xIdx = qMin(m_WidthSize - 1, xIdx);

    yIdx = qMax(0, yIdx);
    yIdx = qMin(m_HeightSize - 1, yIdx);

    m_ctrl->SelectChecked(xIdx, yIdx);

    update();
}



///
/// \brief CheckerboardWidget::MoveBall
/// 绘制小球移动
///
/// \param path
/// 小球移动的路径
///
void CheckerboardWidget::MoveBall(QStack<QPoint> path)
{

}
